package com.my;

import java.util.Random;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.midlet.MIDlet;

public class Looping extends GameCanvas implements Runnable {
	Graphics g;
	private int kursorMenu=1;
	private int inputDelay = 0;
	private int angka = 0;
	Random acak = new Random();
	
	private MIDlet parent;
	
	public long GameFrameDelay = 30;
	Thread thread = new Thread(this);

	protected Looping(MIDlet parent) {
		super(true);
		this.setFullScreenMode(true);
		g = getGraphics();
		this.parent = parent;
		// TODO Auto-generated constructor stub
	}

	public void paintBack() {
		g.setColor(139, 139, 139);
		g.fillRect(0, 0, getWidth(), getHeight());
	}

	public void tulisAwal() {
		g.setColor(0, 0, 0);
		g.drawString("Masukan nomornya:", 0, 0, 0);
	}

	public void kursorAngka(int angka){
		g.setColor(255, 255, 255);
		g.drawString(""+kursorMenu, getWidth()/2, getHeight()/3, 0);
		
		if (++inputDelay > 2) {
			int keyState = getKeyStates();

			if((keyState & DOWN_PRESSED) != 0){
				if (kursorMenu == 1) {
					kursorMenu = 20;
				}else {
					kursorMenu-=1;
				}
			}

			if((keyState & UP_PRESSED) != 0){
				if (kursorMenu == 20) {
					kursorMenu = 1;
				}else {
					kursorMenu+=1;
				}
			}
			
			if((keyState & FIRE_PRESSED) != 0){
				System.out.println("Anda menjawab : " + kursorMenu);
				if(kursorMenu < angka)
					System.out.println("Ternyata tebakan Anda terlalu kecil!");
				else if(kursorMenu > angka)
					System.out.println("Ternyata tebakan Anda terlalu besar");
				else
				{
					System.out.println("Benar");
					parent.notifyDestroyed();
				}
			}
			inputDelay = 0;
		}
	}

	public void startGame() {
		thread.start();
	}
		    
	public void stopGame() {
		thread = null;
	}

	public void run() {
		// TODO Auto-generated method stub
		angka  = acak.nextInt(19)+1;
		System.out.println(angka);
		while (true) {
			paintBack();
			tulisAwal();
			kursorAngka(angka);
			try {
				Thread.sleep(GameFrameDelay);
			}catch (InterruptedException ie) {
				stopGame();
			}
			flushGraphics();
		}
	}
}